//
// Created by 崔世强 on 2018/4/2.
// Copyright (c) 2018 Facebook. All rights reserved.
//

import Foundation
import SwiftyJSON
import WCDBSwift

class DelMemberHandler: NoticeHandlerProtocol {
    static let instance = DelMemberHandler()

    private init() {
    }

    func handler(_ msg: Message) {
        do {
            let db = SQLiteHelper.getDb()
            try db.run(transaction: { _ in

                let json = JSON(parseJSON: msg.content ?? "")
                var needDelId = [Int]()
                for userIdJson in json["userIds"].arrayValue {
                    let userId = userIdJson.intValue
                    needDelId.append(userId)
                    if userId == AppStatusManager.instance.userLoginStatus.1 ?? 0 {
                        try GroupDao.updateKickout(msg.sessionServerId,kickout:true)
                        let dic:[String:Any] = ["groupId":msg.sessionServerId,"kickout":true]
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: kNoteChatMsgGroupMemberChange), object: dic)
                    }
                }
                try GroupDao.delete(msg.sessionServerId, userIds: needDelId)
            })

        } catch {
            print(error)
        }
    }

    func show(_ msg: ChatMessage) -> String? {
        do {
            let db = SQLiteHelper.getDb()
            var returnStr = ""
            try db.run(transaction: { _ in
                let manager = try ContactDao.getContact(msg.from)
                let memberOfManager = try GroupDao.getMember(msg.sessionId, userId: msg.from)

                let json = JSON(parseJSON: msg.text ?? "")
                var delMembers = [String]()
                for userIdJson in json["userIds"].arrayValue {
                    let userId = userIdJson.intValue
                    let userContact = try ContactDao.getContact(userId)
                    let member = try GroupDao.getMember(msg.sessionId, userId: userId)
                    var name = userContact?.remarkName ?? member?.nickName ?? userContact?.name ?? ""
                    if userId == AppStatusManager.instance.userLoginStatus.1 ?? 0 {
                        name = "你"
                    }
                    returnStr.append(name)
                    delMembers.append(name)
                }

                var name = manager?.remarkName ?? memberOfManager?.nickName ?? manager?.name
                if msg.isMe {
                    name = "你"
                }
                returnStr = "\(name ?? "管理员" ) 将 \(delMembers) 移出本群"
            })

            return returnStr

        } catch {
            return msg.text
        }
    }
}
